import axios from "axios";
import { Message } from "iview";
import router from "@/router";
import store from "@/store";
import { loadRemove, localRead } from "@/libs/util";

const API_BASE_URL = import.meta.env.DEV ? "/adminapi" : import.meta.env.VITE_API_BASE_URL || `${location.origin}`;
const service = axios.create({
    baseURL: API_BASE_URL,
    timeout: 90000, // 请求超时时间 ~~~
});
axios.defaults.withCredentials = true; // 携带cookie

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        config.baseURL = API_BASE_URL;
        // 后端接口拿不到json请求参数
        // if (config.file) {
        //     config.headers["Content-Type"] = "multipart/form-data";
        // }
        const token = store.getters.getToken;
        if (token) {
            config.headers["Authorization"] = "Bearer " + token;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    },
);

// response interceptor
service.interceptors.response.use(
    (response) => {
        let obj = {};
        if (!!response.data) {
            if (typeof response.data == "string") {
                obj = JSON.parse(response.data);
            } else {
                obj = response.data;
            }
        }
        let code = response.data ? obj.code : 0;
        switch (code) {
            case 200:
                return Promise.resolve(obj.data);
            case 401:
                store.dispatch("doLoginOut");
                router.replace({ name: "login" });
                return Promise.reject(obj || { msg: "error" });
                break;
            default:
                showError(obj?.msg || "error");
                return Promise.reject(obj || { msg: "error" });
        }
    },
    (error) => {
        showError(error.msg || "error");
        return Promise.reject(error);
    },
);

function showError(msg) {
    Message.error(msg);
}
export default service;
